package com.retail.member.client.impl;

import cn.hutool.core.util.ObjectUtil;
import com.retail.core.entity.result.Result;
import com.retail.member.client.MsgClient;
import com.retail.msg.entity.request.RetailMsgRequest;
import com.retail.msg.entity.vo.RetailMsgVo;
import com.retail.msg.service.RetailMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MsgClientImpl implements MsgClient {

    @Autowired
    private RetailMsgService retailMsgService;

    @Override
    public Result<List<RetailMsgVo>> findMsgList(RetailMsgRequest request) {
        List<RetailMsgVo> retailMsgs = retailMsgService.findMsgLikeMsgUser(request.getMsgUser(), request.getMsgContent());
        List<RetailMsgVo> res = new ArrayList<>();
        for (RetailMsgVo vo : retailMsgs) {
            if (ObjectUtil.isNotEmpty(vo) ) {
                if (ObjectUtil.isEmpty(vo.getMsgUser())) {
                    res.add(vo);
                } else {
                    String msgUser = vo.getMsgUser();
                    List<String> msgUsers = Arrays.stream(msgUser.split(",")).collect(Collectors.toList());
                    if (ObjectUtil.contains(msgUsers, request.getMsgUser())) {
                        res.add(vo);
                    }
                }
            }
        }
        return Result.success(res);
    }

    @Override
    public Result<RetailMsgVo> detail(Long id) {
        RetailMsgVo retailDetail = retailMsgService.getModel(id);
        return Result.success(retailDetail);
    }

    @Override
    public Result<RetailMsgVo> updateStatus(Long id, String adminId) {
        retailMsgService.updateState(id, adminId);
        return Result.success();
    }

    @Override
    public Result<List<RetailMsgVo>> findTop5(String adminId) {
        List<RetailMsgVo> retailMsgs = retailMsgService.findMsgLikeMsgUser(adminId, "");
        List<RetailMsgVo> res = new ArrayList<>();
        for(Integer i =0 ; i< 5;i++) {
            RetailMsgVo vo = retailMsgs.get(i);
            if (ObjectUtil.isNotEmpty(vo) ) {
                if (ObjectUtil.isEmpty(vo.getMsgUser())) {
                    res.add(vo);
                } else {
                    String msgUser = vo.getMsgUser();
                    List<String> msgUsers = Arrays.stream(msgUser.split(",")).collect(Collectors.toList());
                    if (ObjectUtil.contains(msgUsers, adminId+"")) {
                        res.add(vo);
                    }
                }
            }
        }
        return Result.success(res);
    }
}
